#ifndef ENCODE_HANDLER
#define ENCODE_HANDLER

#include "tools.h"
#include "encoder.h"
#include "thread_handler.h"
#include "avpacket_list.h"
#include <mutex>

namespace lcf
{

    class EncodeHandler : public ThreadHandler
    {
    public:
        EncodeHandler() : curPts_(-1),
                          timeBase_(nullptr),
                          curMs_(0),
                          blockSize_(0),
                          syncPts_(-1),
                          isOpen_(false),
                          streamIndex_(0),
                          needView_(false),
                          isCache_(false) {}
        ~EncodeHandler() {}

        /// 打开解码器
        bool Open(AVCodecParameters *para);

        // 责任链处理函数
        void HandleTask(AVPacket *pkt) override;

        // 线程主函数
        void Main() override;

        /// 清理缓存
        void Clear();

        void Stop();

        long long GetCurMs() { return curMs_; };

        void SetStreamIndex(int index) { streamIndex_ = index; }
        void SetIsCache(bool isCache) { isCache_ = isCache; }
        void SetSyncPts(long long syncPts) { syncPts_ = syncPts; }
        void SetBlockSize(int blockSize) { blockSize_ = blockSize; }
        void SetTimeBase(AVRational *timeBase)
        {
            if (!timeBase)
                return;
            std::unique_lock<std::mutex> lock(mtx_);
            if (timeBase_)
                delete timeBase_;
            timeBase_ = new AVRational();
            timeBase_->den = timeBase->den;
            timeBase_->num = timeBase->num;
        }

    private:
        long long curPts_; // 当前解码到的pts（以解码数据为准）
        AVRational *timeBase_;
        long long curMs_;   // 当前播放位置的毫秒
        int blockSize_;     // 阻塞大小
        long long syncPts_; // 同步时间 -1不同步
        bool isOpen_;
        int streamIndex_;
        std::mutex mtx_;
        Encoder encoder_;
        AVPacketList pktList_;
        bool needView_;                  // 是否需要渲染，每帧只渲染一次，通过GetFrame
        std::list<AVFrame *> frameList_; // 存储音频缓冲
        AVFrame *frame_;
        bool isCache_; // 是否缓冲frame队列
    };
}

#endif